package com.thingcom.delinrobot.utils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
     * WiFi连接管理
     * 申请权限
     * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
     * <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
     * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
     * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
     * 动态权限
     * Manifest.permission.ACCESS_COARSE_LOCATION
     * Manifest.permission.ACCESS_FINE_LOCATION
     *
     */
    public class WifiUtils {
        private static WifiUtils utils = null;
        private WifiInfo currentWifiInfo;
        private Context mContext;

        public WifiUtils(Context context){
            wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            mContext = context.getApplicationContext();
        }

        public static WifiUtils getInstance(Context context){
            if (utils == null){
                synchronized (WifiUtils.class){
                    if (utils == null){
                        utils = new WifiUtils(context);
                    }
                }
            }
            return utils;
        }

        private WifiManager wifiManager;

        /**
         * wifi是否打开
         * @return
         */
        public boolean isWifiEnable(){
            boolean isEnable = false;
            if (wifiManager != null){
                if (wifiManager.isWifiEnabled()){
                    currentWifiInfo = getCurrentWifiInfo();
                    isEnable = true;
                }
            }
            return isEnable;
        }

        /**
         * 打开WiFi
         */
        public void openWifi(){
            if (wifiManager != null && !isWifiEnable()){
                wifiManager.setWifiEnabled(true);
            }
        }

        /**
         * 关闭WiFi
         */
        public void closeWifi(){
            if (wifiManager != null && isWifiEnable()){
                wifiManager.setWifiEnabled(false);
            }
        }

        /**
         * 获取WiFi列表
         * @return
         */
        public List<ScanResult> getWifiList(){
            wifiManager.startScan();
            List<ScanResult> resultList = new ArrayList<>();
            if (wifiManager != null && isWifiEnable()){
                resultList.addAll(wifiManager.getScanResults());
            }
            return resultList;
        }

        /**
         * 有密码连接
         * @param ssid
         * @param pws
         */
        public void connectWifiPws(String ssid, String pws){

            WifiConfiguration conf = new WifiConfiguration();
            String ssid1 = "\"" + ssid + "\"";
            conf.SSID = ssid1;
            conf.preSharedKey = "\""+ pws +"\"";

           //链接wifi
            wifiManager.addNetwork(conf);
            List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
            for (WifiConfiguration i : list) {
                if (i.SSID != null && i.SSID.equals(ssid1)) {
                    Log.i("yufeng", "connectWifiPws: "+i);
                  //  wifiManager.disconnect();   如果不注释，每次点击都要同意改变Wifi状态
                    wifiManager.enableNetwork(i.networkId, true);
                    wifiManager.reconnect();
                    break;
                }
            }
//            wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
//            int netId = wifiManager.addNetwork(getWifiConfig(ssid, pws, true));
//            wifiManager.enableNetwork(netId, true);
        }

        /**
         * 无密码连接
         * @param ssid
         */
        public void connectWifiNoPws(String ssid){
            wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
            int netId = wifiManager.addNetwork(getWifiConfig(ssid, "", false));
            wifiManager.enableNetwork(netId, true);
        }

        /**
         * wifi设置
         * @param ssid
         * @param pws
         * @param isHasPws
         */
        private WifiConfiguration getWifiConfig(String ssid, String pws, boolean isHasPws){
            WifiConfiguration config = new WifiConfiguration();
            config.allowedAuthAlgorithms.clear();
            config.allowedGroupCiphers.clear();
            config.allowedKeyManagement.clear();
            config.allowedPairwiseCiphers.clear();
            config.allowedProtocols.clear();
            config.SSID = "\"" + ssid + "\"";

            WifiConfiguration tempConfig = isExist(ssid);
            if(tempConfig != null) {
                wifiManager.removeNetwork(tempConfig.networkId);
            }
            if (isHasPws){
                config.preSharedKey = "\""+pws+"\"";
                config.hiddenSSID = true;
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                config.status = WifiConfiguration.Status.ENABLED;
            }else {
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            }
            return config;
        }

        /**
         * 得到配置好的网络连接
         * @param ssid
         * @return
         */
        private WifiConfiguration isExist(String ssid) {
            List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
            for (WifiConfiguration config : configs) {
                if (config.SSID.equals("\""+ssid+"\"")) {
                    return config;
                }
            }
            return null;
        }




    /**
     * 获取当前WiFi信息
     * @return
     */

    public WifiInfo getCurrentWifiInfo() {
        if (wifiManager != null) {
            currentWifiInfo = wifiManager.getConnectionInfo();
        }
        return currentWifiInfo;
    }

    /**
     * 注册广播
     */
    public void registBroadcast(){
        IntentFilter filter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mContext.registerReceiver(mReceiver,filter);
    }

    /**
     * 注销广播
     */
    public void unRegisterBroadcast(){
        try{
            mContext.unregisterReceiver(mReceiver);
        }catch (IllegalArgumentException ex){
            //广播没有注册
            ex.printStackTrace();
        }

    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver()  {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            switch (action) {
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    //下面这句话好像已经不起作用，直接使用currentWifiInfo
                    //   WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
                    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                        if (wifiStateCallback != null) {
                            // currentWifiInfo = wifiInfo;
                            String a = getWIFISSID();
                            wifiStateCallback.onWifiChange(a);
                        }
                        MyLog.i("wifi", "wifi断开");
                    } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        //获取当前wifi名称
                        MyLog.i("wifi", "连接到网络 " + wifiInfo.getSSID());
                        if (wifiStateCallback != null){
                            // currentWifiInfo = wifiInfo;
                            String a = getWIFISSID();
                            wifiStateCallback.onWifiChange(a);
                            MyLog.i("onReceive: ", "onReceive: "+
                                    "currentWifiInfo:"+currentWifiInfo);
                        }
                    }

                    break;
            }
        }
    };

    private WifiStateCallback wifiStateCallback;

    public void setWifiStateCallback(WifiStateCallback wifiStateCallback) {
        this.wifiStateCallback = wifiStateCallback;
    }

    public interface WifiStateCallback{
        void onWifiChange(String info);
    }

    /**
     * 获取SSID
     * @param
     * @return  WIFI 的SSID
     */
    public String getWIFISSID() {
        String ssid = "<unknown ssid>";
        if (Build.VERSION.SDK_INT <= 26 || Build.VERSION.SDK_INT == 28||Build.VERSION.SDK_INT == 29) {
            WifiManager mWifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            assert mWifiManager != null;
            WifiInfo info = mWifiManager.getConnectionInfo();
            MyLog.i("wifi", "getWIFISSID: " +info);

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                return info.getSSID();
            } else {
                return info.getSSID().replace("\"", "");
            }
        } else if (Build.VERSION.SDK_INT == 27) {
            ConnectivityManager connManager = (ConnectivityManager) mContext.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            assert connManager != null;
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected()) {
                if (networkInfo.getExtraInfo() != null) {
                    return networkInfo.getExtraInfo().replace("\"", "");
                }
            }
        }
        return ssid;
    }
}



//        public String getWIFISSID() {
//        String ssid="unknown id";
//
//            assert wifiManager != null;
//            WifiInfo info = wifiManager.getConnectionInfo();
//            ConnectivityManager connManager = (ConnectivityManager) mContext.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
//            String name = info.getSSID().replace("\"", "");
//
//            assert connManager != null;
//            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
//            if (networkInfo.isConnected()) {
//                if (networkInfo.getExtraInfo()!=null){
//                    ssid = networkInfo.getExtraInfo().replace("\"","");
//                }
//            }
//            if (name. equals("<unknown ssid>")){
//                return ssid;
//            } else {
//                return name;
//
//    }


